package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.CompanyDTO;
import com.example.joblinker.entity.Company;
import com.example.joblinker.entity.User;
import com.example.joblinker.entity.Job;
import com.example.joblinker.mapper.CompanyMapper;
import com.example.joblinker.mapper.UserMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.service.CompanyService;
import com.example.joblinker.vo.CompanyVO;
import com.example.joblinker.vo.JobVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.stream.Collectors;
import java.util.Collections;
import java.util.List;

@Service
public class CompanyServiceImpl implements CompanyService {

    @Resource
    private CompanyMapper companyMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private JobMapper jobMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CompanyVO createCompany(CompanyDTO companyDTO, Long userId) {
        // 查询用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 创建公司
        Company company = new Company();
        BeanUtils.copyProperties(companyDTO, company);
        company.setUserId(userId);
        company.setStatus(1); // 默认为正常状态
        companyMapper.insert(company);

        // 更新用户关联的公司ID
        user.setCompanyId(company.getId());
        userMapper.updateById(user);

        return convertToVO(company);
    }

    @Override
    public CompanyVO getCompanyDetail(Long id) {
        Company company = companyMapper.selectById(id);
        if (company == null) {
            throw new RuntimeException("公司不存在");
        }
        return convertToVO(company);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CompanyVO updateCompany(Long id, CompanyDTO companyDTO, Long userId) {
        // 查询公司
        Company company = companyMapper.selectById(id);
        if (company == null) {
            throw new RuntimeException("公司不存在");
        }

        // 校验权限
        if (!company.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作");
        }

        // 记录原始名称和Logo，用于检查是否有变更
        String oldName = company.getName();
        String oldLogo = company.getLogo();

        // 更新公司
        BeanUtils.copyProperties(companyDTO, company);
        companyMapper.updateById(company);

        // 如果公司名称或Logo发生变化，则同步更新所有相关职位的冗余字段
        if (!company.getName().equals(oldName) || !company.getLogo().equals(oldLogo)) {
            // 查询该公司的所有职位
            LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Job::getCompanyId, company.getId());
            List<Job> jobs = jobMapper.selectList(queryWrapper);
            
            // 更新每个职位的公司名称和Logo
            if (jobs != null && !jobs.isEmpty()) {
                for (Job job : jobs) {
                    job.setCompanyName(company.getName());
                    job.setCompanyLogo(company.getLogo());
                    jobMapper.updateById(job);
                }
            }
        }

        return convertToVO(company);
    }

    @Override
    public Page<CompanyVO> getCompanyList(Integer page, Integer size) {
        // 创建分页对象
        Page<Company> companyPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<Company>()
                .eq(Company::getStatus, 1)
                .orderByDesc(Company::getCreateTime);

        // 执行查询
        companyMapper.selectPage(companyPage, queryWrapper);

        // 转换结果
        Page<CompanyVO> voPage = new Page<>();
        BeanUtils.copyProperties(companyPage, voPage, "records");
        voPage.setRecords(companyPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    public CompanyVO getCompanyByUserId(Long userId) {
        // 先从用户表中查找用户关联的公司ID
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 如果用户没有关联公司，则返回null
        if (user.getCompanyId() == null || user.getCompanyId() <= 0) {
            return null;
        }
        
        // 查询公司信息
        Company company = companyMapper.selectById(user.getCompanyId());
        if (company == null) {
            return null;
        }
        
        return convertToVO(company);
    }

    @Override
    public Page<JobVO> getCompanyJobs(Long companyId, Integer status, Integer page, Integer size) {
        // 检查公司是否存在
        Company company = companyMapper.selectById(companyId);
        if (company == null) {
            throw new RuntimeException("公司不存在");
        }
        
        // 创建分页参数
        Page<Job> pageParams = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Job::getCompanyId, companyId);
        
        // 如果指定了状态，则添加状态过滤条件
        if (status != null) {
            queryWrapper.eq(Job::getStatus, status);
        }
        
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(Job::getCreateTime);
        
        // 查询职位数据
        Page<Job> jobPage = jobMapper.selectPage(pageParams, queryWrapper);
        
        // 转换为VO
        Page<JobVO> voPage = new Page<>(jobPage.getCurrent(), jobPage.getSize(), jobPage.getTotal());
        
        // 如果有数据，转换每一条记录
        if (jobPage.getRecords() != null && !jobPage.getRecords().isEmpty()) {
            // 调用JobService中的方法转换为VO
            List<JobVO> voList = jobPage.getRecords().stream()
                    .map(job -> {
                        JobVO vo = new JobVO();
                        BeanUtils.copyProperties(job, vo);
                        // 设置公司信息
                        vo.setCompanyName(company.getName());
                        vo.setCompanyLogo(company.getLogo());
                        return vo;
                    })
                    .collect(Collectors.toList());
            
            voPage.setRecords(voList);
        } else {
            voPage.setRecords(Collections.emptyList());
        }
        
        return voPage;
    }

    /**
     * 将实体转换为VO
     */
    private CompanyVO convertToVO(Company company) {
        CompanyVO vo = new CompanyVO();
        BeanUtils.copyProperties(company, vo);
        return vo;
    }
} 